package fr.imag.adele.mediation.probes.impl;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.StringTokenizer;

import org.osgi.framework.BundleContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

import fr.imag.adele.mediation.probes.services.DataCollector;
import fr.imag.adele.mediation.probes.services.Probe;
import fr.imag.adele.mediation.probes.util.DataEvent;
import fr.imag.adele.mediation.probes.util.DataSet;

public class StandardDataCollector implements DataCollector, EventHandler {		
	private String	 		m_requiredResources;		
	private DataSet 		m_localDataSet = new DataSet();	
	
	private BundleContext 	m_bundleContext;		
	private Probe 			m_parentProbe;
	
	public StandardDataCollector(BundleContext bc){
		this.m_bundleContext = bc;		
	}
	public void setParentProbe(Probe probe){
		this.m_parentProbe = probe;
	}
	public Probe getParentProbe(){
		return m_parentProbe;
	}
	public DataSet getCollectedData() {
		// TODO we should make a clone and remove all elements.
		DataSet dataSet = new DataSet();
		for (int i=0; i<m_localDataSet.size();i++){
			dataSet.add(m_localDataSet.getDataEvent(i));			
		}
		m_localDataSet.removeAllEvents();
		//dataSet = m_localDataSet.getCopy();		
		return dataSet;
	}	
	public void handleEvent(Event event) {
		System.out.println("Receiving...");
		DataEvent dataEvent = new DataEvent(event.getProperty(DataEvent.CP_EVENT_RESOURCE).toString(),
				event.getProperty(DataEvent.CP_EVENT_SOURCE).toString(),
				event.getProperty(DataEvent.CP_EVENT_TIMESTAMP).toString(),
				event.getProperty(DataEvent.CP_EVENT_VALUE),
				event.getProperty(DataEvent.CP_EVENT_UNIT).toString(),null);
		m_localDataSet.add(dataEvent);
		if (getParentProbe()!=null && getParentProbe().getScheduler() != null){
			getParentProbe().getScheduler().notify(dataEvent);
		} else {
			System.out.println("No Scheduler found!");
		}
	}
	public String removeSpaces(String s) {
		  StringTokenizer st = new StringTokenizer(s," ",false);
		  String t="";
		  while (st.hasMoreElements()) t += st.nextElement();
		  return t;
		  }

	public void start(){
		Dictionary dico = new Hashtable();		
		m_requiredResources = removeSpaces(m_requiredResources);
		String[] resources = m_requiredResources.split(",");
		
		dico.put(EventConstants.EVENT_TOPIC, resources);		
		m_bundleContext.registerService(EventHandler.class.getName(), this, dico);
		System.out.println("Starting DataCollector with topics : ");
		
		for (int i=0; i<resources.length; i++){
			System.out.println("- " + resources[i]);
		}
	}
	public void stop(){
		
	}
}
